package com.chalk.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.chalk.common.constant.CommonConstants;
import com.chalk.common.exception.ServiceException;
import com.chalk.common.util.IdGenerator;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import com.chalk.config.base.BaseController;
import com.chalk.config.security.UserDetailsUtil;
import com.chalk.model.SysPermission;
import com.chalk.model.SysUser;
import com.chalk.model.SysUserRoleRelated;
import com.chalk.service.SysPermissionService;
import com.chalk.service.SysRoleService;
import com.chalk.service.SysUserRoleRelatedService;
import com.chalk.vo.MenuTree;
import com.chalk.vo.SysPermissionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统权限表(SysPermission)表控制层
 *
 * @author maxiaoqiang
 * @since 2019-03-28 17:19:38
 */
@Api(value = "系统权限表接口", tags = "系统权限表模块")
@RestController
@RequestMapping("/v1/sysPermission")
public class SysPermissionController extends BaseController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysUserRoleRelatedService userRoleRelatedService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 系统权限表列表
     *
     * @param current       当前页数
     * @param size          每页显示条数
     * @param sysPermission 查询实体
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询系统权限表列表", notes = "查询系统权限表列表", response = Result.class)
    @GetMapping
    public Result selectAll(Integer current, Integer size, SysPermission sysPermission) {
        sysPermission.setIsDeleted(CommonConstants.IsDeleted.NOTDEL.getValue());
        return Result.success(this.sysPermissionService.selectPage(this.getPage(current, size), new EntityWrapper <SysPermission>(sysPermission)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询系统权限表", notes = "查询系统权限表", response = Result.class)
    @GetMapping("{id}")
    public Result selectOne(
            @ApiParam(name = "id", value = "主键", required = true, example = "1")
            @PathVariable String id) {
        return Result.success(this.sysPermissionService.selectById(id));
    }


    /**
     * 保存系统权限表
     *
     * @param sysPermission 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "保存sysPermission", notes = "保存sysPermission", response = Result.class)
    @PostMapping
    public Result insert(
            @ApiParam(name = "sysPermission", value = "传入json格式", required = true)
            @RequestBody @Valid SysPermissionVo sysPermission, BindingResult result) {
        beanValidator(result);
        beanValidate(sysPermission);
        sysPermission.setPermId(IdGenerator.getIdStr());
        DateTime date = DateUtil.date();
        sysPermission.setCreateTime(date);
        sysPermission.setUpdateTime(date);
        return Result.success(this.sysPermissionService.insert(sysPermission));
    }

    /**
     * 修改系统权限表
     *
     * @param sysPermission 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "修改系统权限表", notes = "修改系统权限表", response = Result.class)
    @PutMapping
    public Result update(
            @ApiParam(name = "sysPermission", value = "传入json格式", required = true)
            @RequestBody @Valid SysPermissionVo sysPermission, BindingResult result) {
        beanValidator(result);
        beanValidate(sysPermission);
        sysPermission.setUpdateTime(DateUtil.date());
        return Result.success(this.sysPermissionService.updateById(sysPermission));
    }

    /**
     * 权限名唯一校验
     *
     * @param permission
     */
    private void beanValidate(SysPermissionVo permission) {
        int count = this.sysPermissionService.selectCount(new EntityWrapper <SysPermission>()
                .eq("perm_name", permission.getPermName())
                .eq("is_deleted", CommonConstants.IsDeleted.NOTDEL.getValue())
                .ne("perm_id", permission.getPermId() == null ? "" : permission.getPermId()));
        if (count > 0) {
            throw new ServiceException(ResultCode.NAME_REPEAT);
        }
    }

    /**
     * 逻辑删除系统权限表
     *
     * @param ids 主键集合
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "批量删除系统权限表", notes = "批量删除系统权限表", response = Result.class)
    @DeleteMapping
    public Result delete(
            @ApiParam(name = "ids", value = "传数组", required = true)
            @RequestBody String[] ids) {
        return Result.success(this.sysPermissionService.deleteBatchByPrimaryKey(ids));
    }

    private Page <SysPermission> getPage(Integer current, Integer size) {
        Page <SysPermission> page = new Page <>();
        if (current != null) {
            page.setCurrent(current);
        }
        if (size != null) {
            page.setSize(size);
        }
        return page;
    }


    /**
     * 查询所有菜单
     *
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询所有菜单", notes = "查询所有菜单", response = Result.class)
    @PostMapping("/getTree")
    public Result getTree() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        String id = sysRoleService.getRoleByUser(username).getRoleId();
        List <MenuTree> menuTrees=new ArrayList <>();
        if(id.equals(CommonConstants.ROOT_ROLE_ID)){

            menuTrees  = this.sysPermissionService.getTree(id);
        }else {
            menuTrees=this.sysPermissionService.getTreeByRoleId(id,CommonConstants.ROOT_ROLE_ID);
        }


        return Result.success(menuTrees);
    }


    /**
     * 查询用户权限树
     *
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询用户权限树", notes = "查询用户权限树", response = Result.class)
    @PostMapping("/menuUserTree")
    public Result menuUserTree(
            @ApiParam(name = "SysPermission", value = "查询参数", required = false)
            @RequestBody MenuTree menuTree) {
        /* 获取操作用户 */
        SysUser sysUser = (SysUser) UserDetailsUtil.getUserInfo("sysUserService", "user_name");
        List <SysUserRoleRelated> relateds = userRoleRelatedService.selectList(new EntityWrapper <SysUserRoleRelated>().eq("user_id", sysUser.getUserId()));
        List <String> roleIds = new ArrayList <>();
        relateds.forEach(dto -> {
            if (CommonConstants.ROOT_ROLE_ID.equals(dto.getRoleId())) {
                menuTree.setBigger(0);
            } else {
                roleIds.add(dto.getRoleId());
            }
        });
        menuTree.setPermId(CommonConstants.ROOT_ID);
        menuTree.setRoleIds(roleIds);
        List <MenuTree> menuTrees = this.sysPermissionService.selectUserTree(menuTree);
        return Result.success(menuTrees);
    }

    @ApiOperation(value = "查询用户权限树", notes = "查询用户权限树", response = Result.class)
    @PostMapping("/getUserMenu")
    public Result getUserMenu() {
        /* 获取操作用户 */
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        String id = sysRoleService.getRoleByUser(username).getRoleId();
        MenuTree menuTree = new MenuTree();
        menuTree.setRoleId(id);
        List <MenuTree> menuTrees = sysPermissionService.selectUserTree(id);
        return Result.success(menuTrees);
    }


    /**
     * 查询系统权限树(带用户标识)
     *
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询系统权限树(带用户标识)", notes = "查询系统权限树(带用户标识)", response = Result.class)
    @PostMapping("/menuMarkTree")
    public Result menuMarkTree(
            @ApiParam(name = "SysPermission", value = "查询参数", required = false)
            @RequestBody MenuTree param) {
        if (CommonConstants.ROOT_ROLE_ID.equals(param.getRoleId())) {
            param.setBigger(0);
        } else {
            param.setRoleId(param.getRoleId());
        }
        param.setPermId(CommonConstants.ROOT_ID);
        List <MenuTree> menuTrees = this.sysPermissionService.selectMenuMarkTree(param);
        return Result.success(menuTrees);
    }

    /**
     * 查询系统权限树(带用户标识)
     *
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询系统权限树(带用户标识)", notes = "查询系统权限树(带用户标识)", response = Result.class)
    @PostMapping("/menuMarkTreeUser")
    public Result menuMarkTreeUser(
            @ApiParam(name = "SysPermission", value = "查询参数", required = false)
            @RequestBody MenuTree param) {
        SysUser sysUser = (SysUser) UserDetailsUtil.getUserInfo("sysUserService", "user_name");
        List <SysUserRoleRelated> relateds = userRoleRelatedService.selectList(new EntityWrapper <SysUserRoleRelated>().eq("user_id", sysUser.getUserId()));
        List <String> roleIds = new ArrayList <>();
        relateds.forEach(dto -> {
            if (CommonConstants.ROOT_ROLE_ID.equals(dto.getRoleId())) {
                param.setBigger(0);
            } else {
                roleIds.add(dto.getRoleId());
            }
        });
        param.setUserId(sysUser.getUserId());
        param.setPermId(CommonConstants.ROOT_ID);
        List <MenuTree> menuTrees = this.sysPermissionService.selectMenuMarkTree(param);
        return Result.success(menuTrees);
    }

}